package com.huanqiu.mylib.util;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public final class ImageUtil {

    public static String bitmap2File(@NonNull Context context, @NonNull Bitmap bmp, @Nullable File destDir) {
        File dir = destDir == null ? context.getCacheDir() : destDir;
        File file = new File(dir, System.currentTimeMillis() + ".jpg");
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 80, fos);
            // bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
            IOUtils.closeQuietly(fos);
            return null;
        }
        return file.getAbsolutePath();
    }

    /**
     * 保存图片到系统相册
     *
     * MediaStore on Android 10
     */
    @Nullable
    public static String saveImageToPublicPictureDirectory(@NonNull Context context, @NonNull String filepath) {
        return Util.getStorageMode() == 1
                ? _saveImage(context, filepath)
                : _saveImage10(context, filepath);
    }

    /**
     * 保存图片到系统相册
     */
    @Nullable
    public static String saveImageToPublicPictureDirectory(@NonNull Context context, Bitmap bmp) {
        return Util.getStorageMode() == 1
                ? _saveImage(context, bmp)
                : _saveImage10(context, bmp);
    }

    private static String _saveImage(Context context, String filepath) {
        String _destDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/" + Util.getAppName(context);

        File destDir = new File(_destDir);
        if (!destDir.exists()) {
            destDir.mkdir();
        }

        File destFile = new File(destDir, System.currentTimeMillis() + ".png");
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(filepath);
            fos = new FileOutputStream(destFile);
            IOUtils.copy(fis, fos);
            fis.close();
            fos.close();

            // 把文件插入到系统图库
            // MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), filename, null);

            // 保存图片后发送广播通知系统更新数据库
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(destFile)));
        } catch (IOException e) {
            e.printStackTrace();
            IOUtils.closeQuietly(fis);
            IOUtils.closeQuietly(fos);
            return null;
        }

        return destFile.getAbsolutePath();
    }

    @RequiresApi(api = SystemVersion.Android_10)
    private static String _saveImage10(Context context, String filepath) {
        if (Build.VERSION.SDK_INT < SystemVersion.Android_10) return null;

        if (TextUtils.isEmpty(filepath)) return null;

        ContentResolver contentResolver = context.getContentResolver();
        ContentValues contentValues = _genContentValues(context, filepath);
        Uri uri = contentResolver.insert(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                contentValues
        );
        if (uri == null) return null;

        FileInputStream fis = null;
        OutputStream os = null;
        try {
            fis = new FileInputStream(filepath);
            os = contentResolver.openOutputStream(uri);
            IOUtils.copy(fis, os);
            fis.close();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
            IOUtils.closeQuietly(fis);
            IOUtils.closeQuietly(os);
            return null;
        }

        MediaStoreUtil.finishPending(context, uri);

        return uri.toString();
    }

    /**
     * https://www.jianshu.com/p/8cede074ba5b
     */
    private static String _saveImage(Context context, Bitmap bmp) {
        String _destDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/" + Util.getAppName(context);

        File destDir = new File(_destDir);
        if (!destDir.exists()) {
            destDir.mkdir();
        }

        File destFile = new File(destDir, System.currentTimeMillis() + ".png");
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(destFile);
            bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.close();

            // 把文件插入到系统图库
            // MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), filename, null);

            // 保存图片后发送广播通知系统更新数据库
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(destFile)));
        } catch (IOException e) {
            e.printStackTrace();
            IOUtils.closeQuietly(fos);
            return null;
        }

        return destFile.getAbsolutePath();
    }

    @RequiresApi(api = SystemVersion.Android_10)
    private static String _saveImage10(Context context, Bitmap bmp) {
        if (Build.VERSION.SDK_INT < SystemVersion.Android_10) return null;

        ContentResolver contentResolver = context.getContentResolver();
        ContentValues contentValues = _genContentValues(context, bmp);
        Uri uri = contentResolver.insert(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                contentValues
        );
        if (uri == null) return null;

        OutputStream os = null;
        try {
            os = contentResolver.openOutputStream(uri);
            bmp.compress(Bitmap.CompressFormat.PNG, 100, os);
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
            IOUtils.closeQuietly(os);
            return null;
        }

        MediaStoreUtil.finishPending(context, uri);

        return uri.toString();
    }

    @RequiresApi(api = SystemVersion.Android_10)
    private static ContentValues _genContentValues(Context context, String filepath) {
        ContentValues cv = new ContentValues();

        String name = System.currentTimeMillis() + "." + FileUtil.getSuffixName(filepath);

        cv.put(MediaStore.MediaColumns.DISPLAY_NAME, name);
        cv.put(MediaStore.MediaColumns.MIME_TYPE, "image/*");
        cv.put(MediaStore.MediaColumns.RELATIVE_PATH, _getRelativePath(context)); // 保存路径

        cv.put(MediaStore.MediaColumns.IS_PENDING, true);

        return cv;
    }

    @RequiresApi(api = SystemVersion.Android_10)
    private static ContentValues _genContentValues(Context context, Bitmap bmp) {
        ContentValues cv = new ContentValues();

        String name = System.currentTimeMillis() + ".png";

        cv.put(MediaStore.MediaColumns.DISPLAY_NAME, name);
        cv.put(MediaStore.MediaColumns.MIME_TYPE, "image/*");
        cv.put(MediaStore.MediaColumns.RELATIVE_PATH, _getRelativePath(context)); // 保存路径

        cv.put(MediaStore.MediaColumns.IS_PENDING, true);

        return cv;
    }

    private static String _getRelativePath(Context context) {
        return Environment.DIRECTORY_PICTURES + "/" + Util.getAppName(context);
    }

}
